package org.liquidByte.trafficMustang.androidApp.activities;

import java.io.Serializable;

import android.os.Bundle;

public abstract class ModelActivity<T extends Serializable> extends AbstractActivity {
	private T model;
	private boolean nullAllowed;
	private boolean lookup;
	private int layoutResource;
	private Class<T> modelClass;
	
	ModelActivity(int layoutResource, Class<T> modelClass, T model, boolean nullAllowed) {
		super();
		if (model == null) {
			throw new IllegalArgumentException("model cannot be null");
		}
		this.model = model;
		this.nullAllowed = nullAllowed;
		this.lookup = false;
		this.layoutResource = layoutResource;
		this.modelClass = modelClass;
	}
	ModelActivity(int layoutResource, Class<T> modelClass, boolean nullAllowed) {
		this.nullAllowed = nullAllowed;
		this.lookup = true;
		this.layoutResource = layoutResource;
		this.modelClass = modelClass;
	}
	
	protected T getModel() {
		return model;
	}
	protected void setModel(T value) {
		if (value == null && !this.isNullAllowed()) {
			throw new IllegalArgumentException("model cannot be null");
		}
		if (!(this.model == null && value == null ||
			  this.model != null && value != null && this.model.equals(value))) {
			this.model = value;
			this.bindToView();
		} else {
			this.model = value;
		}		
	}
	protected boolean isNullAllowed() {
		return nullAllowed;
	}
	
	protected abstract void bindToView();
	
	@SuppressWarnings("unchecked")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(this.layoutResource);
		Bundle bundle = this.getIntent().getExtras();
		
		T model = null;
		if (bundle != null && this.lookup) {
			model = (T)bundle.getSerializable(this.modelClass.getName());
		}
		this.setModel(model);
	}
}
